//
//  GuestLoginManager.m
//  ebook
//
//  Created by 吴超飞 on 16/5/23.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "GuestLoginManager.h"
#import "FileManager.h"

@implementation GuestLoginManager

+(void)loginWithGuest:(void(^)(void))complete{
    
    [GuestLoginManager guestLoginSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        complete();
    } failed:^(int stateCode, NSString *failMsg) {
    }];
}

+(void)guestLoginSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    NSString *guest = [GuestLoginManager guestName];
    if(!guest||guest.length<4)return;//获取失败时无法自动登录，使用手动注册登录流程
    [EbookNetRequest guestLoginWithName:guest success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        
        ((AppDelegate *)[UIApplication sharedApplication].delegate).checkver = [dict[@"data"][@"checkver"] integerValue]==1;
        NSString *token = dict[@"data"][@"token"];
        BOOL lock = [dict[@"data"][@"lock"] integerValue]==1;//自动游客登录时服务端返回 lock = 0;
        [[NSUserDefaults standardUserDefaults] setObject:guest forKey:kUserName];
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kPassword];
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:kToken];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsGuest];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsLogin];
        [[NSUserDefaults standardUserDefaults] setBool:lock forKey:kIsUnLock];
        [[NSUserDefaults standardUserDefaults] setObject:[GuestLoginManager ToHex:dict[@"data"][@"expTime"]] forKey:kExptime];
        [[NSUserDefaults standardUserDefaults] setInteger:([[NSDate date]timeIntervalSince1970]+24*3600*30) forKey:kVipOverTime];//模拟过期时间
        [[NSUserDefaults standardUserDefaults] setFloat:[[NSDate date]timeIntervalSince1970] forKey:kLoginTime];
        [[NSUserDefaults standardUserDefaults] synchronize];
        successBlock(stateCode,successMsg,dict);
    } failed:^(int stateCode, NSString *failMsg) {
        failedBlock(stateCode,failMsg);
        MTLog(@"#warning 自动登录失败！");
    }];
}

+(NSString *)guestName{
    
    NSString *guest = [EbookNetRequest AD_UUID];
    guest = guest.length>12?[[guest stringByReplacingOccurrencesOfString:@"-" withString:@""] substringFromIndex:12]:nil;
    return guest;
}

//网络请求自动登录
+(void)autoLoginSuccess:(RequestSuccessed)successBlock failed:(RequestFailed)failedBlock{
    
    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:kIsLogin];
    BOOL isGuest = [[NSUserDefaults standardUserDefaults] boolForKey:kIsGuest];
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:kUserName];
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:kPassword];
    BOOL isHasUserPsw = userName&&password&&userName.length>0&&password.length>0;
    
    if (isLogin&&!isGuest&&isHasUserPsw){//曾经登录过,且非游客,则使用用户名密码自动登录
        [EbookNetRequest loginWithName:userName passsword:password success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
            [self loginSuccessWithName:userName passsword:password dict:dict];
            if(successBlock)successBlock(stateCode,successMsg,dict);
        } failed:^(int stateCode, NSString *failMsg) {
            if(failedBlock)failedBlock(stateCode,failMsg);
        }];
    }else{//其他情况一律再做一次游客登录
        
        [GuestLoginManager guestLoginSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
            [self loginSuccessWithName:userName passsword:password dict:dict];
            if(successBlock)successBlock(stateCode,successMsg,dict);
        } failed:^(int stateCode, NSString *failMsg) {
            if(failedBlock)failedBlock(stateCode,failMsg);
        }];
    }
}

//自动登录，直接返回登录结果
+(void)autoLogin:(void(^)(BOOL issuc))complete{
    
    [GuestLoginManager autoLoginSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        
        if(complete)complete(YES);
        MTLog(@"自动登录成功");
    } failed:^(int stateCode, NSString *failMsg) {
        if(complete)complete(NO);
         MTLog(@"自动登录失败：%@",failMsg);
    }];
}

+(void)loginWithName:(NSString *) userName passsword:(NSString *) password success:(void(^)(BOOL suc))successBlock failed:(void(^)(int stateCode , NSString *failMsg))failedBlock{
    
    [EbookNetRequest loginWithName:userName passsword:password success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
       
        [self loginSuccessWithName:userName passsword:password dict:dict];
        if(successBlock)successBlock(YES);
    } failed:^(int stateCode, NSString *failMsg) {
       
        if(successBlock)successBlock(NO);
        if(failedBlock)failedBlock(stateCode,failMsg);
    }];
}

+(void)registerWithName:(NSString *) userName passsword:(NSString *) password success:(void(^)(BOOL suc))successBlock failed:(void(^)(int stateCode , NSString *failMsg))failedBlock{
   
    if (![[NSUserDefaults standardUserDefaults] boolForKey:kIsGuest]) {//普通注册
        [EbookNetRequest registerWithName:userName passsword:password success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
            
            [self loginSuccessWithName:userName passsword:password dict:dict];
            if(successBlock)successBlock(YES);
            
        } failed:^(int stateCode, NSString *failMsg) {
            
            if(successBlock)successBlock(NO);
            if(failedBlock)failedBlock(stateCode,failMsg);
        }];
    }else{//绑定注册
        [EbookNetRequest blindCurentGuestWithName:userName passsword:password success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
            
            [self loginSuccessWithName:userName passsword:password dict:dict];
            if(successBlock)successBlock(YES);
            
        } failed:^(int stateCode, NSString *failMsg) {
            
            if(successBlock)successBlock(NO);
            if(failedBlock)failedBlock(stateCode,failMsg);
        }];
    }
}

//根据用户名密码登录或注册成功的处理
+(void)loginSuccessWithName:(NSString *) userName passsword:(NSString *) password  dict:(NSDictionary *)dict{
    
    ((AppDelegate *)[UIApplication sharedApplication].delegate).checkver = [dict[@"data"][@"checkver"] integerValue]==1;
    NSString *token = dict[@"data"][@"token"];
    NSString *user = userName;
    BOOL lock = [dict[@"data"][@"lock"] integerValue]==1;
    [[NSUserDefaults standardUserDefaults] setObject:user?user:@"" forKey:kUserName];
    [[NSUserDefaults standardUserDefaults] setObject:password?password:@"" forKey:kPassword];
    [[NSUserDefaults standardUserDefaults] setObject:token?token:@"" forKey:kToken];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsLogin];
    [[NSUserDefaults standardUserDefaults] setBool:(password==nil||(password&&password.length==0)) forKey:kIsGuest];
    [[NSUserDefaults standardUserDefaults] setBool:lock forKey:kIsUnLock];
    [[NSUserDefaults standardUserDefaults] setObject:[GuestLoginManager ToHex:dict[@"data"][@"expTime"]] forKey:kExptime];
    [[NSUserDefaults standardUserDefaults] setFloat:[[NSDate date]timeIntervalSince1970] forKey:kLoginTime];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(void)changeUserComplete{
    /**
     *  切换账号，清理没有离线的book数据
     */
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [FileManager clearBookData];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:kFreshLocalshelNotification object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateBookshelfNotification object:nil];
        });
    });
}

//十进制转十六进制
+(NSString *)ToHex:(NSString *)tmp
{
    long long int tmpid = [tmp intValue];
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;  
        }  
        
    }  
    return str;  
}

@end
